<template>
  <div class="score-management-container">
    <h1>{{ isStudent ? '我的成绩' : '学生成绩管理' }}</h1>

    <!-- 成绩概览卡片 -->
    <div class="score-overview" v-if="scoreList.length > 0">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-card class="overview-card">
            <template #header>
              <div class="card-header">
                <span>总课程数</span>
                <el-tag type="info" size="small">统计</el-tag>
              </div>
            </template>
            <div class="card-content">
              <span class="number">{{ uniqueCourses.length }}</span>
              <span class="label">门课程</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="overview-card">
            <template #header>
              <div class="card-header">
                <span>平均学分</span>
                <el-tag type="success" size="small">统计</el-tag>
              </div>
            </template>
            <div class="card-content">
              <span class="number">{{ averageCredit }}</span>
              <span class="label">学分/课程</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="overview-card">
            <template #header>
              <div class="card-header">
                <span>总学分</span>
                <el-tag type="warning" size="small">统计</el-tag>
              </div>
            </template>
            <div class="card-content">
              <span class="number">{{ totalCredits }}</span>
              <span class="label">学分</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="overview-card">
            <template #header>
              <div class="card-header">
                <span>平均成绩</span>
                <el-tag type="danger" size="small">统计</el-tag>
              </div>
            </template>
            <div class="card-content">
              <span class="number">{{ overallAverage }}</span>
              <span class="label">分</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="overview-card credit-gpa-card">
            <template #header>
              <div class="card-header">
                <span>学分绩</span>
                <el-tag type="primary" size="small">GPA</el-tag>
              </div>
            </template>
            <div class="card-content">
              <span class="number credit-gpa-number">{{ creditGPA }}</span>
              <span class="label">点</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="overview-card">
            <template #header>
              <div class="card-header">
                <span>更新学分绩</span>
                <el-tag type="success" size="small">操作</el-tag>
              </div>
            </template>
            <div class="card-content">
              <el-button type="primary" size="small" @click="calculateCreditGPA" :loading="creditGPALoading">
                <el-icon><Refresh /></el-icon>
                计算
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="header-actions">
      <div class="left-actions">
        <el-input
          v-if="isAdmin"
          v-model="searchId"
          placeholder="请输入成绩ID"
          class="search-input"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button-group v-if="isAdmin">
          <el-button type="primary" @click="handleSearchById">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button type="success" @click="showAddDialog">
            <el-icon><Plus /></el-icon>添加成绩
          </el-button>
          <el-button type="danger" @click="handleRemoveAll">
            <el-icon><Delete /></el-icon>删除全部
          </el-button>
        </el-button-group>
      </div>

      <div class="right-actions">
        <el-button-group>
          <el-button type="primary" @click="sumExportData">
            <el-icon><ChatLineSquare /></el-icon>成绩分析
          </el-button>
          <el-button type="primary" @click="handleExportData">
            <el-icon><Download /></el-icon>导出Excel
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 成绩列表 -->
    <el-table :data="scoreList" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="stuId" label="学号" width="100"></el-table-column>
      <el-table-column prop="stuName" label="学生姓名" width="120"></el-table-column>
      <el-table-column prop="team" label="学期" width="100"></el-table-column>
      <el-table-column prop="courseSerialNumber" label="课程序号" width="120"></el-table-column>
      <el-table-column prop="courseName" label="课程名称" width="120"></el-table-column>
             <el-table-column prop="score" label="分数" width="100"></el-table-column>
       <el-table-column prop="credit" label="学分" width="100"></el-table-column>
       <el-table-column prop="gradeCategory" label="成绩类别" width="120"></el-table-column>

      <el-table-column v-if="isAdmin" label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleRemoveById(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      v-if="isAdmin"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.current"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pagination.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      style="margin-top: 20px; text-align: right;"
    ></el-pagination>

    <!-- 添加/编辑成绩对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑成绩' : '添加成绩'"
      width="500px"
    >
      <el-form :model="scoreForm" :rules="rules" ref="scoreFormRef" label-width="80px">
        <el-form-item label="学号" prop="stuId">
          <el-input v-model.number="scoreForm.stuId"></el-input>
        </el-form-item>
        <el-form-item label="学生姓名" prop="stuName">
          <el-input v-model="scoreForm.stuName"></el-input>
        </el-form-item>
        <el-form-item label="学期" prop="team">
          <el-input v-model="scoreForm.team"></el-input>
        </el-form-item>
        <el-form-item label="课程序号" prop="courseSerialNumber">
          <el-input v-model="scoreForm.courseSerialNumber"></el-input>
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="scoreForm.courseName"></el-input>
        </el-form-item>
        <el-form-item label="分数" prop="score">
          <el-input v-model.number="scoreForm.score" type="number" min="0" max="100"></el-input>
        </el-form-item>
        <el-form-item label="学分" prop="credit">
          <el-input v-model.number="scoreForm.credit" type="number" min="0"></el-input>
        </el-form-item>
        <el-form-item label="成绩类别" prop="gradeCategory">
          <el-select v-model="scoreForm.gradeCategory" placeholder="请选择成绩类别">
            <el-option label="平时成绩" value="平时成绩"></el-option>
            <el-option label="期中成绩" value="期中成绩"></el-option>
            <el-option label="期末成绩" value="期末成绩"></el-option>
            <el-option label="总评成绩" value="总评成绩"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Delete, Download, Edit, ChatLineSquare, Refresh } from '@element-plus/icons-vue';
import scoreAPI from '../api/score.js';

// 数据
const scoreList = ref([]);
const searchId = ref('');
const dialogVisible = ref(false);
const isEdit = ref(false);
const scoreFormRef = ref(null); // 表单引用
const creditGPA = ref('0.0'); // 学分绩
const creditGPALoading = ref(false); // 学分绩计算加载状态
const scoreForm = reactive({
  id: null,
  stuId: null,
  stuName: '',
  team: '',
  courseSerialNumber: '',
  courseName: '',
  score: null,
  credit: null,
  gradeCategory: '',
});
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
});

// 用户信息
const userRole = ref(localStorage.getItem('role') || 'admin');
const userStuId = ref(localStorage.getItem('stuId') || '0');
const userName = ref(localStorage.getItem('name') || '');
const isStudent = computed(() => userRole.value === 'student');
const isAdmin = computed(() => userRole.value === 'admin');

// 计算属性：获取唯一课程列表
const uniqueCourses = computed(() => {
  const courses = new Set();
  scoreList.value.forEach(score => {
    courses.add(score.courseName);
  });
  return Array.from(courses);
});

// 计算属性：计算平均学分
const averageCredit = computed(() => {
  if (scoreList.value.length === 0) return 0;
  const total = scoreList.value.reduce((sum, score) => sum + (score.credit || 0), 0);
  return (total / uniqueCourses.value.length).toFixed(1);
});

// 计算属性：计算总学分
const totalCredits = computed(() => {
  return scoreList.value.reduce((sum, score) => sum + (score.credit || 0), 0);
});

// 计算属性：计算总平均分（使用加权平均）
const overallAverage = computed(() => {
  if (scoreList.value.length === 0) return 0;
  
  // 按课程分组并计算加权平均
  const courseGroups = {};
  scoreList.value.forEach(score => {
    if (!courseGroups[score.courseName]) {
      courseGroups[score.courseName] = {
        totalWeightedScore: 0,
        totalCredits: 0
      };
    }
    const weightedScore = (score.score || 0) * (score.credit || 0);
    courseGroups[score.courseName].totalWeightedScore += weightedScore;
    courseGroups[score.courseName].totalCredits += (score.credit || 0);
  });

  // 计算所有课程的总加权平均
  let totalWeightedScore = 0;
  let totalCredits = 0;
  
  Object.values(courseGroups).forEach(group => {
    if (group.totalCredits > 0) {
      totalWeightedScore += group.totalWeightedScore;
      totalCredits += group.totalCredits;
    }
  });

  return totalCredits > 0 ? (totalWeightedScore / totalCredits).toFixed(1) : '0.0';
});

// 根据分数获取颜色
// 获取学分标签类型
const rules = reactive({
  stuId: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { type: 'number', message: '学号必须是数字', trigger: 'blur' },
  ],
  stuName: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' },
  ],
  team: [
    { required: true, message: '请输入学期', trigger: 'blur' },
  ],
  courseSerialNumber: [
    { required: true, message: '请输入课程序号', trigger: 'blur' },
  ],
  courseName: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
  ],
  credit: [
    { required: true, message: '请输入学分', trigger: 'blur' },
    { type: 'number', message: '学分必须是数字', trigger: 'blur' },
  ],
  gradeCategory: [
    { required: true, message: '请输入成绩类别', trigger: 'blur' },
  ],
  score: [
    { required: true, message: '请输入分数', trigger: 'blur' },
    { type: 'number', message: '分数必须是数字', trigger: 'blur' },
  ],
});

  // 方法
const fetchScores = async () => {
  try {
    console.log('开始获取成绩列表...');
    let response;

    if (isStudent.value) {
      // 学生获取自己的所有成绩
      response = await scoreAPI.getAllScores();
    } else {
      // 管理员分页获取
      response = await scoreAPI.getPage(pagination.current, pagination.size);
    }

    console.log('API完整响应:', response);

    // 验证响应对象的结构
    if (!response || !response.data) {
      throw new Error('API响应格式错误');
    }

    const { code, data, message, msg } = response.data;

    // 处理成功响应 (code为1表示成功)
    if (code === 1 && data) {
      if (isStudent.value) {
        // 学生视图
        if (Array.isArray(data)) {
          scoreList.value = data;
          pagination.total = data.length;
        } else {
          throw new Error('学生成绩数据格式错误');
        }
      } else {
        // 管理员视图
        if (data.records && typeof data.total === 'number') {
          scoreList.value = data.records;
          pagination.total = data.total;
        } else {
          throw new Error('分页数据格式错误');
        }
      }
      console.log('成绩列表获取成功，数据条数:', scoreList.value.length);
      
      // 成功获取成绩后，自动计算学分绩
      if (isStudent.value && scoreList.value.length > 0) {
        calculateCreditGPA();
      }
      
      return true;
    } 
    
    // 处理业务提示信息（code=0表示业务失败但非系统错误，如未找到成绩）
    if (code === 0) {
      const infoMsg = message || msg || '未找到成绩信息';
      console.log('业务提示:', infoMsg);
      scoreList.value = [];
      pagination.total = 0;
      
      // Only show message if not a student (admin might want to see empty list silently)
      if (!isStudent.value) {
        ElMessage.info(infoMsg);
      }
      return true;
    }
    
    // 处理真正的业务错误（code为负数）
    if (code < 0) {
      const errorMsg = message || msg || '获取成绩列表失败';
      console.error('API返回错误:', errorMsg);
      console.error('API响应数据:', data);
      ElMessage.error(errorMsg);
      return false;
    }

    // 其他未知状态码
    console.error('未知响应状态码:', code);
    ElMessage.error('未知错误，请重试');
    return false;

  } catch (error) {
    // 处理网络错误或其他异常
    console.error('获取成绩列表出错:', error.message);
    console.error('错误详情:', error);
    console.error('错误堆栈:', error.stack);

    let errorMessage = '获取成绩列表失败';
    if (error.response?.status === 404) {
      errorMessage = '服务器接口未找到';
    } else if (error.response?.status === 401) {
      errorMessage = '未授权访问';
    } else if (error.response?.status === 403) {
      errorMessage = '没有权限访问';
    }

    ElMessage.error(errorMessage);
    return false;
  }
};

const handleSearchById = async () => {
  if (!searchId.value) {
    ElMessage.warning('请输入要搜索的成绩ID');
    fetchScores(); // 如果清空搜索框，则重新加载所有数据
    return;
  }
  try {
    const response = await scoreAPI.getById(searchId.value);
    if (response.data.code === 1 && response.data.data && response.data.data.length > 0) {
      scoreList.value = response.data.data;
      pagination.total = response.data.data.length; // 搜索结果只有一条或几条，总数就是结果数量
      pagination.current = 1; // 搜索结果回到第一页
    } else {
      scoreList.value = [];
      pagination.total = 0;
      ElMessage.warning(response.data.message || '未找到该ID的成绩信息');
    }
  } catch (error) {
    console.error('搜索成绩出错:', error);
    ElMessage.error('搜索成绩网络请求失败');
  }
};

const showAddDialog = () => {
  isEdit.value = false;
  // 重置表单
  scoreForm.id = null;
  scoreForm.stuId = null;
  scoreForm.stuName = '';
  scoreForm.team = '';
  scoreForm.courseSerialNumber = '';
  scoreForm.courseName = '';
  scoreForm.score = null;
  scoreForm.credit = null;
  scoreForm.gradeCategory = '';
  if (scoreFormRef.value) {
    scoreFormRef.value.resetFields();
  }
  dialogVisible.value = true;
};

const showEditDialog = (row) => {
  isEdit.value = true;
  // 填充表单
  scoreForm.id = row.id;
  scoreForm.stuId = row.stuId;
  scoreForm.stuName = row.stuName;
  scoreForm.team = row.team;
  scoreForm.courseSerialNumber = row.courseSerialNumber;
  scoreForm.courseName = row.courseName;
  scoreForm.score = row.score;
  scoreForm.credit = row.credit;
  scoreForm.gradeCategory = row.gradeCategory;
  dialogVisible.value = true;
};

const submitForm = () => {
  scoreFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = isEdit.value 
          ? await scoreAPI.update(scoreForm)
          : await scoreAPI.save(scoreForm);
        if (response.data.code === 1) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功');
          dialogVisible.value = false;
          fetchScores(); // 刷新列表
        } else {
          ElMessage.error(response.data.message || (isEdit.value ? '更新失败' : '添加失败'));
        }
      } catch (error) {
        console.error('提交表单出错:', error);
        ElMessage.error('提交表单网络请求失败');
      }
    } else {
      ElMessage.warning('请检查表单填写');
      return false;
    }
  });
};

const handleRemoveById = (id) => {
  ElMessageBox.confirm('确定要删除这条成绩信息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const response = await scoreAPI.removeById(id);
        if (response.data.code === 1) {
          ElMessage.success('删除成功');
          fetchScores(); // 刷新列表
        } else {
          ElMessage.error(response.data.message || '删除失败');
        }
      } catch (error) {
        console.error('删除成绩出错:', error);
        ElMessage.error('删除成绩网络请求失败');
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
};

const handleRemoveAll = () => {
  ElMessageBox.confirm('确定要删除所有成绩信息吗？此操作不可逆！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error',
  })
    .then(async () => {
      try {
        const response = await scoreAPI.removeAll();
        if (response.data.code === 1) {
          ElMessage.success('所有成绩已删除');
          fetchScores(); // 刷新列表
        } else {
          ElMessage.error(response.data.message || '删除所有成绩失败');
        }
      } catch (error) {
        console.error('删除所有成绩出错:', error);
        ElMessage.error('删除所有成绩网络请求失败');
      }
    })
    .catch(() => {
      ElMessage.info('已取消操作');
    });
};

const handleSizeChange = (newSize) => {
  pagination.size = newSize;
  pagination.current = 1; // 改变每页大小后回到第一页
  fetchScores();
};

const handleCurrentChange = (newPage) => {
  pagination.current = newPage;
  fetchScores();
};

// 导出数据为Excel文件
const handleExportData = async () => {
  try {
    // 验证用户信息
    if (!userRole.value) {
      ElMessage.warning('请先登录再进行导出操作');
      return;
    }

    if (isStudent.value) {
      if (!userName.value || userName.value.trim() === '') {
        ElMessage.warning('无法导出：未获取到用户名信息，请重新登录');
        return;
      }
      if (!userStuId.value) {
        ElMessage.warning('无法导出：未获取到学号信息，请重新登录');
        return;
      }
    }

    let response;
    try {
      if (isStudent.value) {
        console.log('开始导出学生成绩，用户名:', userName.value);
        response = await scoreAPI.exportStudentData(userName.value);
      } else {
        console.log('开始导出所有成绩');
        response = await scoreAPI.exportAdminData();
      }
    } catch (error) {
      console.error('导出请求失败:', error);
      if (error.response?.status === 404) {
        ElMessage.error('导出失败：接口未找到，请联系管理员');
      } else if (error.response?.status === 400) {
        ElMessage.error('导出失败：请求参数错误，请检查用户信息是否完整');
      } else if (error.response?.status === 401) {
        ElMessage.error('导出失败：未授权，请重新登录');
      } else if (error.response?.status === 403) {
        ElMessage.error('导出失败：没有权限执行此操作');
      } else {
        ElMessage.error('导出失败：' + (error.response?.data?.message || '未知错误'));
      }
      return;
    }

    // 检查响应
    if (!response || !response.data) {
      ElMessage.error('导出失败：未收到有效的文件数据');
      return;
    }
    // 获取文件名
    const contentDisposition = response.headers['content-disposition'];
    let filename = isStudent.value ? '我的成绩.xlsx' : '所有成绩.xlsx';
    if (contentDisposition) {
      const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(contentDisposition);
      if (matches != null && matches[1]) {
        filename = decodeURIComponent(matches[1].replace(/['"]/g, ''));
      }
    }

    // 创建下载链接
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();

    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success('导出成功');
    console.log('文件导出成功:', filename);
  } catch (error) {
    console.error('文件处理失败:', error);
    ElMessage.error('文件处理失败，请重试');
  }
};
const sumExportData = async () => {
  try {
    // 验证用户信息
    if (!userRole.value) {
      ElMessage.warning('请先登录再进行计算操作');
      return;
    }

    // 调用后端API计算平均分
    const response = await scoreAPI.calculateAverages(isStudent.value ? userStuId.value : null);
    
    if (!response || !response.data) {
      throw new Error('计算失败：服务器响应无效');
    }

    const { code, data, message } = response.data;

    if (code !== 1 || !data) {
      throw new Error(message || '计算失败');
    }

    // 格式化结果显示
    const resultMessage = data.map(result => {
      const avgScore = Number(result.averageScore).toFixed(2);
      const weightedAvg = result.weightedAverage ? `，加权平均分：${Number(result.weightedAverage).toFixed(2)}` : '';
      return `${result.team} ${result.courseName}: 
        平均分：${avgScore}${weightedAvg}
        (共${result.count}条成绩，总学分：${result.totalCredits || 0})`
    }).join('\n\n');

    // 创建统计视图，区分学生端和管理员端
    const statisticsHtml = isStudent.value ? `
      <div class="statistics-container">
        <div class="statistics-header">成绩统计</div>
        <div class="student-statistics">
          <div class="student-info">
            <h3>${userName.value || '未知学生'}</h3>
            <div class="statistics-summary">
              <div class="summary-item">
                <span class="label">总课程数：</span>
                <span class="value">${data.length}门</span>
              </div>
              <div class="summary-item">
                <span class="label">总学分：</span>
                <span class="value">${data.reduce((sum, result) => sum + (result.totalCredits || 0), 0)}分</span>
              </div>
              <div class="summary-item average-score">
                <span class="label">总平均分：</span>
                <span class="value">${(() => {
                  const totalWeightedScore = data.reduce((sum, result) => 
                    sum + (Number(result.averageScore) * (result.totalCredits || 0)), 0);
                  const totalCredits = data.reduce((sum, result) => 
                    sum + (result.totalCredits || 0), 0);
                  return totalCredits > 0 ? (totalWeightedScore / totalCredits).toFixed(1) : '0.0';
                })()}分</span>
              </div>
            </div>
          </div>
          <div class="course-list">
            ${data.map(result => `
              <div class="course-item">
                <span class="course-name">${result.courseName}</span>
                <span class="course-score">${Number(result.averageScore).toFixed(1)}分</span>
              </div>
            `).join('')}
          </div>
        </div>
      </div>
    ` : `
      <div class="statistics-container">
        <div class="statistics-header">成绩统计详情</div>
        ${data.map(result => `
          <div class="course-statistics">
            <h4>${result.team} - ${result.courseName}</h4>
            <div class="stats-grid">
              <div>平均分：${Number(result.averageScore).toFixed(2)}</div>
              ${result.weightedAverage ? `<div>加权平均分：${Number(result.weightedAverage).toFixed(2)}</div>` : ''}
              <div>最高分：${result.maxScore || 'N/A'}</div>
              <div>最低分：${result.minScore || 'N/A'}</div>
              <div>总人数：${result.count}</div>
              <div>总学分：${result.totalCredits || 0}</div>
            </div>
          </div>
        `).join('')}
      </div>
    `;

    ElMessageBox.alert(statisticsHtml, '成绩统计分析', {
      confirmButtonText: '确定',
      dangerouslyUseHTMLString: true,
      customClass: 'statistics-dialog'
    });

  } catch (error) {
    console.error('计算平均分出错:', error);
    ElMessage.error('计算平均分失败：' + error.message);
  }
};

// 计算学分绩的方法
const calculateCreditGPA = async () => {
  try {
    creditGPALoading.value = true;
    
    // 验证用户信息
    if (!userRole.value) {
      ElMessage.warning('请先登录再进行计算操作');
      return;
    }

    // 获取学号，学生只能计算自己的学分绩
    const stuIdToCalculate = isStudent.value ? parseInt(userStuId.value) : null;
    
    if (isStudent.value && !stuIdToCalculate) {
      ElMessage.warning('未能获取学号信息，请重新登录');
      return;
    }

    // 调用后端API计算学分绩
    const response = await scoreAPI.calculateCreditScore(stuIdToCalculate);
    
    if (!response || !response.data) {
      throw new Error('计算失败：服务器响应无效');
    }

    const { code, data, message } = response.data;

    if (code === 1 && data !== undefined) {
      // 成功获取学分绩
      creditGPA.value = Number(data).toFixed(2);
      ElMessage.success('学分绩计算成功！');
      console.log('学分绩计算成功:', creditGPA.value);
    } else {
      // 处理错误情况
      const errorMsg = message || '计算学分绩失败';
      console.error('计算学分绩失败:', errorMsg);
      ElMessage.error(errorMsg);
      creditGPA.value = '0.0';
    }

  } catch (error) {
    console.error('计算学分绩出错:', error);
    ElMessage.error('计算学分绩失败：' + (error.message || '未知错误'));
    creditGPA.value = '0.0';
  } finally {
    creditGPALoading.value = false;
  }
};

// 生命周期钩子
onMounted(() => {
  fetchScores(); // 页面加载时获取初始数据
});
</script>

<style scoped>
.score-management-container {
  padding: 20px;
}
.header-actions {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.score-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.score-overview {
  margin-bottom: 20px;
  
  .overview-card {
    background: #fff;
    border-radius: 8px;
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      color: #606266;
    }

    .card-content {
      text-align: center;
      padding: 10px 0;

      .number {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin-right: 8px;
      }

      .label {
        font-size: 14px;
        color: #909399;
      }
    }
    
    /* 学分绩卡片特殊样式 */
    &.credit-gpa-card {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      
      .card-header {
        color: white;
      }
      
      .card-content {
        .credit-gpa-number {
          color: #FFD700;
          font-size: 28px;
          text-shadow: 0 1px 3px rgba(0,0,0,0.3);
        }
        
        .label {
          color: rgba(255,255,255,0.9);
        }
      }
      
      &:hover {
        transform: translateY(-3px) scale(1.02);
        box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
      }
    }
  }
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);

  .left-actions {
    display: flex;
    gap: 16px;
    align-items: center;

    .search-input {
      width: 250px;
    }
  }

  .right-actions {
    display: flex;
    gap: 16px;
  }
}

.score-table {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  
  .score-cell {
    padding: 4px 0;
  }
  
  .el-progress {
    margin: 0;
  }
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
}

.dialog-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}

.statistics-dialog {
  max-width: 600px !important;
  .el-message-box__content {
    max-height: 70vh;
    overflow-y: auto;
  }

  .student-statistics {
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;

    .student-info {
      text-align: center;
      margin-bottom: 24px;
      padding-bottom: 16px;
      border-bottom: 1px solid #ebeef5;

      h3 {
        color: #303133;
        margin: 0 0 20px 0;
        font-size: 20px;
      }

      .statistics-summary {
        display: flex;
        justify-content: space-around;
        margin-bottom: 16px;
        
        .summary-item {
          text-align: center;
          
          .label {
            display: block;
            color: #909399;
            font-size: 14px;
            margin-bottom: 4px;
          }
          
          .value {
            font-size: 20px;
            font-weight: bold;
            color: #303133;
          }
          
          &.average-score .value {
            color: #409EFF;
            font-size: 24px;
          }
        }
      }
    }

    .course-list {
      .course-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        margin-bottom: 8px;
        background: white;
        border-radius: 4px;
        transition: all 0.3s;

        &:hover {
          transform: translateX(4px);
          box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .course-name {
          color: #606266;
          font-size: 16px;
        }

        .course-score {
          color: #67C23A;
          font-weight: bold;
          font-size: 16px;
        }
      }
    }
  }
}

.statistics-container {
  padding: 16px;
  .statistics-header {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 16px;
    text-align: center;
    color: #409EFF;
  }
}

.course-statistics {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;

  h4 {
    margin: 0 0 12px;
    color: #303133;
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;

    div {
      padding: 8px;
      background: white;
      border-radius: 4px;
      font-size: 14px;
    }
  }
}
</style>